import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:carousel_slider/carousel_slider.dart';
import '../../function/states/encyclopedia_state.dart';
import '../../function/states/user_state.dart';
import '../../function/routes/app_route_manager.dart';
import '../../function/widgets/animated_tap_widget.dart';
import '../../function/widgets/login_dialog.dart';

/// 百科详情页面
class EncyclopediaDetailPage extends StatefulWidget {
  final String encyclopediaId;

  const EncyclopediaDetailPage({super.key, required this.encyclopediaId});

  @override
  State<EncyclopediaDetailPage> createState() => _EncyclopediaDetailPageState();
}

class _EncyclopediaDetailPageState extends State<EncyclopediaDetailPage> {
  int _currentIndex = 0;
  late List<dynamic> _encyclopediaList;

  @override
  void initState() {
    super.initState();

    // 获取当前分类的所有百科数据
    final currentCategory = EncyclopediaState.getCurrentCategory();
    _encyclopediaList =
        currentCategory == 'animal'
            ? EncyclopediaState.getAnimalEncyclopedia()
            : EncyclopediaState.getPlantEncyclopedia();

    // 订阅百科列表变化，实时更新收藏数
    EncyclopediaState.encyclopediaListBeacon.subscribe((encyclopediaList) {
      if (mounted) {
        setState(() {});
      }
    });

    // 订阅用户收藏状态变化
    EncyclopediaState.userFavoritesMapBeacon.subscribe((favoritesMap) {
      if (mounted) {
        setState(() {});
      }
    });

    // 找到当前百科的索引
    _currentIndex = _encyclopediaList.indexWhere(
      (item) => item.encyclopediaId == widget.encyclopediaId,
    );
    if (_currentIndex == -1) _currentIndex = 0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopNavigationBar(),

              SizedBox(height: 12.w),

              // 主要内容
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      // 轮播图
                      _buildImageCarousel(),

                      SizedBox(height: 20.h),

                      // 标签和详情
                      _buildContentSection(),

                      SizedBox(height: 30.h),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 0.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => AppRouteManager.goBack(),
            child: Row(
              children: [
                Icon(Icons.chevron_left, color: Colors.white, size: 26.w),
                SizedBox(width: 12.w),

                // 标题
                Text(_encyclopediaList[_currentIndex].name)
                    .fontSize(18.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                    )
                    .fontWeight(FontWeight.w700)
                    .textAlignment(TextAlign.center),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 获取当前百科的实时收藏数
  int _getCurrentFavoriteCount() {
    return EncyclopediaState.getEncyclopediaById(
          _encyclopediaList[_currentIndex].encyclopediaId,
        )?.favoriteCount ??
        0;
  }

  /// 检查当前用户是否已收藏当前百科
  bool _isCurrentUserFavorite() {
    if (!UserState.checkLoginStatus()) {
      return false; // 未登录用户默认未收藏
    }

    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser == null) {
      return false;
    }

    return EncyclopediaState.isFavorite(
      currentUser.userId,
      _encyclopediaList[_currentIndex].encyclopediaId,
    );
  }

  /// 格式化数字显示
  String _formatCount(int count) {
    if (count < 1000) {
      return count.toString();
    } else {
      double kValue = count / 1000.0;
      if (kValue == kValue.truncate()) {
        // 整数K，如 1000 -> 1K
        return '${kValue.truncate()}K';
      } else {
        // 小数K，如 1100 -> 1.1K
        return '${kValue.toStringAsFixed(1)}K';
      }
    }
  }

  /// 构建图片轮播
  Widget _buildImageCarousel() {
    return CarouselSlider.builder(
      itemCount: _encyclopediaList.length,
      itemBuilder: (context, index, realIndex) {
        final encyclopedia = _encyclopediaList[index];
        return Container(
          margin: EdgeInsets.symmetric(horizontal: 2.w),
          child: AspectRatio(
            aspectRatio: 302 / 348, // 设置宽高比
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25.r),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(25.r),
                child: Stack(
                  children: [
                    // 背景图片
                    Positioned.fill(
                      child: Image.asset(
                        encyclopedia.imageUrl,
                        fit: BoxFit.cover,
                      ),
                    ),

                    // 渐变遮罩 - 从中间到底部
                    Positioned.fill(
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.center,
                            end: Alignment.bottomCenter,
                            colors: [
                              Colors.transparent,
                              Colors.black.withOpacity(0),
                              Colors.black.withOpacity(0.7),
                            ],
                            stops: const [0.0, 0.5, 1.0],
                          ),
                        ),
                      ),
                    ),

                    // 右上角统计信息
                    Positioned(
                      top: 16.h,
                      right: 16.w,
                      child: Column(
                        children: [
                          // 浏览量
                          Container(
                            width: 45.w,
                            padding: EdgeInsets.symmetric(
                              horizontal: 8.w,
                              vertical: 4.h,
                            ),
                            decoration: ShapeDecoration(
                              color: Colors.black.withValues(alpha: 0.40),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12.r),
                              ),
                            ),
                            child: Column(
                              children: [
                                Icon(
                                  Icons.visibility,
                                  color: Colors.white,
                                  size: 20.w,
                                ),
                                SizedBox(width: 4.w),
                                Text(_formatCount(encyclopedia.viewCount))
                                    .fontSize(13.sp)
                                    .textColor(Colors.white)
                                    .fontFamily(
                                      GoogleFonts.quicksand(
                                        fontWeight: FontWeight.w700,
                                      ).fontFamily,
                                    )
                                    .fontWeight(FontWeight.w700),
                              ],
                            ),
                          ),

                          SizedBox(height: 8.h),

                          // 收藏数
                          AnimatedTapWidget(
                            onTap: () {
                              // 检查用户是否已登录
                              if (!UserState.checkLoginStatus()) {
                                // 未登录，显示登录弹窗
                                LoginDialog.show(
                                  context,
                                  title: 'Login Required',
                                  message: 'Please login to add favorites',
                                );
                                return;
                              }

                              // 已登录，切换收藏状态
                              final currentEncyclopedia =
                                  _encyclopediaList[_currentIndex];
                              final currentUser =
                                  UserState.getCurrentUserInfo();
                              if (currentUser != null) {
                                EncyclopediaState.toggleFavorite(
                                  currentUser.userId,
                                  currentEncyclopedia.encyclopediaId,
                                );
                              }
                            },
                            child: Container(
                              width: 45.w,
                              padding: EdgeInsets.symmetric(
                                horizontal: 4.w,
                                vertical: 4.h,
                              ),
                              decoration: ShapeDecoration(
                                color: Colors.black.withValues(alpha: 0.40),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12.r),
                                ),
                              ),
                              child: Column(
                                children: [
                                  Icon(
                                    _isCurrentUserFavorite()
                                        ? Icons
                                            .star // 已收藏：实心星星
                                        : Icons.star_outline, // 未收藏：空心星星
                                    color:
                                        _isCurrentUserFavorite()
                                            ? Colors
                                                .yellow // 已收藏：黄色
                                            : Colors.white, // 未收藏：白色
                                    size: 20.w,
                                  ),
                                  SizedBox(width: 4.w),
                                  Text(_formatCount(_getCurrentFavoriteCount()))
                                      .fontSize(13.sp)
                                      .textColor(Colors.white)
                                      .fontFamily(
                                        GoogleFonts.quicksand(
                                          fontWeight: FontWeight.w700,
                                        ).fontFamily,
                                      )
                                      .fontWeight(FontWeight.w700),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
      options: CarouselOptions(
        height: 350.h, // 设置固定高度
        viewportFraction: 0.75,
        enableInfiniteScroll: true,
        autoPlay: false,
        enlargeCenterPage: true,
        enlargeStrategy: CenterPageEnlargeStrategy.scale,
        initialPage: _currentIndex,
        onPageChanged: (index, reason) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }

  /// 构建内容区域
  Widget _buildContentSection() {
    final currentEncyclopedia = _encyclopediaList[_currentIndex];

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标签
          _buildTags(currentEncyclopedia.tags),

          SizedBox(height: 20.h),

          // 详情描述
          _buildDescription(currentEncyclopedia.description),
        ],
      ),
    );
  }

  /// 构建标签
  Widget _buildTags(List<String> tags) {
    return Wrap(
      spacing: 12.w,
      runSpacing: 8.h,
      children:
          tags.map((tag) {
            return Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 5.h),
              decoration: BoxDecoration(
                color: Colors.transparent,
                borderRadius: BorderRadius.circular(15.r),
                border: Border.all(
                  color: const Color(0xFFFF8A3C),
                  width: 0.5.w,
                ),
              ),
              child: Text(tag)
                  .fontSize(12.sp)
                  .textColor(Colors.white)
                  .fontFamily(
                    GoogleFonts.quicksand(
                      fontWeight: FontWeight.w500,
                    ).fontFamily,
                  )
                  .fontWeight(FontWeight.w500),
            );
          }).toList(),
    );
  }

  /// 构建描述文字
  Widget _buildDescription(String description) {
    return Text(description, style: TextStyle(height: 1.5))
        .fontSize(16.sp)
        .textColor(Colors.white)
        .fontFamily(
          GoogleFonts.quicksand(fontWeight: FontWeight.w500).fontFamily,
        )
        .fontWeight(FontWeight.w500)
        .textAlignment(TextAlign.left);
  }
}
